<template>
  <div class="signature-component">
    <!-- 操作按钮区：根据showButtons字段控制显示隐藏 -->
    <div class="signature-btns" v-if="showButtons">
      <el-button type="primary" size="default" @click="confirmSignature">确认签字</el-button>
      <el-button type="warning" size="default" @click="resetSignature">重新签字</el-button>
      <el-button type="text" size="default" @click="clearCanvas">清除当前</el-button>
    </div>
    <!-- 签字画布区 -->
    <div class="signature-canvas-wrapper">
      <canvas
        ref="signatureCanvas"
        width="1000"
        height="500"
        @mousedown="handleMouseDown"
        @mousemove.stop.prevent="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
      ></canvas>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineEmits, defineExpose, defineProps, type PropType } from 'vue'

// 新增：定义控制按钮显示的props，默认显示
const props = defineProps({
  showButtons: {
    type: Boolean as PropType<boolean>,
    default: true // 默认显示按钮
  }
})

// 定义传递给父组件的事件
const emit = defineEmits<{
  (e: 'signatureConfirm', base64: string): void
}>()

// 画布相关引用与状态
const signatureCanvas = ref<HTMLCanvasElement | null>(null)
let ctx: CanvasRenderingContext2D | null = null
let isPainting = ref(false)
let startX = ref(0)
let startY = ref(0)
let signatureBase64 = ref('') // 存储签字Base64
let hasConfirmed = ref(false) // 标记是否已确认签字

// 组件挂载后初始化画布
onMounted(() => {
  if (signatureCanvas.value) {
    ctx = signatureCanvas.value.getContext('2d') as CanvasRenderingContext2D
    if (ctx) {
      ctx.lineWidth = 2
      ctx.strokeStyle = '#000'
      ctx.lineCap = 'round'
      ctx.lineJoin = 'round'
      ctx.globalAlpha = 1
    }
  }
})

// 获取鼠标相对画布坐标
const getCanvasOffset = (event: MouseEvent) => {
  if (!signatureCanvas.value) return [0, 0]
  const rect = signatureCanvas.value.getBoundingClientRect()
  return [event.clientX - rect.left, event.clientY - rect.top] as [number, number]
}

// 绘制线段
const drawLine = (startX: number, startY: number, endX: number, endY: number) => {
  if (!ctx) return
  ctx.beginPath()
  ctx.moveTo(startX, startY)
  ctx.lineTo(endX, endY)
  ctx.stroke()
  ctx.closePath()
}

// 鼠标按下：开始绘制
const handleMouseDown = (event: MouseEvent) => {
  isPainting.value = true
  const [x, y] = getCanvasOffset(event)
  startX.value = x
  startY.value = y
}

// 鼠标移动：持续绘制
const handleMouseMove = (event: MouseEvent) => {
  if (!isPainting.value || !ctx) return
  const [currentX, currentY] = getCanvasOffset(event)
  drawLine(startX.value, startY.value, currentX, currentY)
  startX.value = currentX
  startY.value = currentY
}

// 鼠标抬起/移出：结束绘制
const handleMouseUp = () => {
  isPainting.value = false
  // 绘制结束后更新Base64
  if (signatureCanvas.value) {
    signatureBase64.value = signatureCanvas.value.toDataURL('image/png')
  }
}

/**
 * 清除当前画布
 */
const clearCanvas = () => {
  if (!signatureCanvas.value || !ctx) return
  const { width, height } = signatureCanvas.value
  ctx.clearRect(0, 0, width, height)
  signatureBase64.value = ''
  alert('已清除当前签字内容！')
}

/**
 * 重新签字（重置全部状态）
 */
const resetSignature = () => {
  clearCanvas()
  hasConfirmed.value = false
  alert('已重置签字区域，可重新绘制！')
}

/**
 * 确认签字（传递Base64给父组件）
 */
const confirmSignature = () => {
  if (!signatureBase64.value) {
    alert('请先完成签字再确认！')
    return
  }
  emit('signatureConfirm', signatureBase64.value)
  hasConfirmed.value = true
  alert('签字已确认，已传递给父组件！')
}

/**
 * 暴露方法给父组件
 */
defineExpose({
  clearCanvas,
  resetSignature,
  confirmSignature,
  getSignatureBase64: () => signatureBase64.value
})
</script>

<style scoped>
.signature-component {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
}

.signature-btns {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.signature-canvas-wrapper {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

canvas {
  background-color: #fff;
  cursor: crosshair;
}
</style>